﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SongClassifier
{
    public partial class FftForm : Form
    {
        int[] value;
        int maxV = 0;
        double[] result_r;
        double[] result_i;

        public FftForm()
        {
            InitializeComponent();
        }

        public FftForm(double[] result_r,double[] result_i)
        {
            InitializeComponent();
            this.result_r = result_r;
            this.result_i = result_i;
            this.panel1.Paint += panel_Paint;
            this.panel1.Resize += panel_Resize;

            AjustSize();
        }


        private void panel_Paint(object sender, PaintEventArgs e)
        {            
            Draw();
        }

        public void panel_Resize(object sender, EventArgs e)
        {
            AjustSize();
            Draw();
        }

        public void AjustSize()
        {
            maxV = 0;
            value = new int[panel1.Width + 1];
            int xLen = this.panel1.Width;
            int ylen = this.panel1.Height;
            int dataLen = result_r.Length;
            int unitSize = (int)Math.Ceiling((dataLen + 0f) / xLen);
            if (unitSize == 0)
                unitSize = 1;
            this.labelUnitSize.Text = unitSize.ToString();

            int avg = 0;
            int count = 0;
            for (int i = 0; i < dataLen; i++)
            {
                avg += (int)Math.Sqrt(result_r[i] * result_r[i] + result_i[i] * result_i[i]);
                if (i % unitSize == unitSize - 1 || i == dataLen - 1)
                {
                    avg /= unitSize;
                    value[count] = avg;
                    if (maxV < Math.Abs(avg))
                        maxV = Math.Abs(avg);
                    count++;
                    avg = 0;
                }
            }
        }

        public void Draw()
        {
            Graphics g = this.panel1.CreateGraphics();
            int x0 = 0;
            int y0 = panel1.Height/2;

            GraphDraw.Draw(g, value, x0, y0, maxV);

        }

        public void SnapShot(double[] result_r, double[] result_i)
        {
            this.result_r = result_r;
            this.result_i = result_i;
            AjustSize();
            Draw();
        }
    }
}
